package com.gugu.procedure.service;

import com.gugu.procedure.bean.Role;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.dao.RoleDao;
import com.gugu.procedure.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class RoleService {

    @Autowired
    private RoleDao roleDao;

    public MessageResult add(Role role) {
        Role bean = roleDao.findTopByName(role.getName());
        if (Objects.nonNull(bean)) {
            return MessageResult.error("当前角色已存在");
        }


        role.setCreateTime(DateUtil.getFormatedDateTime());
        roleDao.save(role);
        return MessageResult.success();
    }

    public MessageResult update(Role role) {
        Role bean = roleDao.findTopByName(role.getName());
        if (Objects.nonNull(bean)) {
            return MessageResult.error("当前角色已存在");
        }
        roleDao.save(role);
        return MessageResult.success();
    }

    public MessageResult listAll() {
        return MessageResult.getSuccessInstance(roleDao.findAll());
    }

    public MessageResult delete(Long roleId) {
        roleDao.deleteById(roleId);
        return MessageResult.success();
    }

    public MessageResult page(String name, int pageNo, int pageSize) {
        Specification<Role> spec = (Specification<Role>) (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasText(name)) {
                list.add(cb.equal(root.get("name").as(String.class), name));
            }
            Predicate[] pre = new Predicate[list.size()];
            query.where(list.toArray(pre));
            return query.getRestriction();
        };
        PageRequest pr = PageRequest.of(pageNo - 1, pageSize, Sort.Direction.DESC, "createTime");
        Page<Role> recordsPage = roleDao.findAll(spec, pr);
        MessageResult mr = MessageResult.success();
        mr.setTotal(recordsPage.getTotalElements());
        mr.setTotalElement(recordsPage.getContent());
        return mr;
    }


}
